package com.rickpan.storage.impl;

import com.rickpan.service.FileStorageService;
import com.rickpan.storage.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.time.Duration;

/**
 * 本地存储服务实现
 * 封装现有的 FileStorageService 逻辑
 */
@Service
@ConditionalOnProperty(name = "app.storage.type", havingValue = "local", matchIfMissing = true)
public class LocalStorageServiceImpl implements StorageService {
    
    private static final Logger logger = LoggerFactory.getLogger(LocalStorageServiceImpl.class);
    
    @Autowired
    private FileStorageService fileStorageService;
    
    @Override
    public String storeFile(MultipartFile file) throws IOException {
        logger.debug("本地存储文件: {}", file.getOriginalFilename());
        return fileStorageService.storeFile(file);
    }

    @Override
    public String initializeChunkUpload(String uploadId, String originalFileName) throws IOException {
        logger.debug("本地存储初始化分片上传: uploadId={}, fileName={}", uploadId, originalFileName);
        // 本地存储不需要特殊的初始化，直接返回成功标识
        return "initialized";
    }
    
    @Override
    public String storeChunk(String uploadId, int chunkIndex, MultipartFile chunk) throws IOException {
        logger.debug("本地存储分片: uploadId={}, chunkIndex={}", uploadId, chunkIndex);
        return fileStorageService.storeChunk(uploadId, chunkIndex, chunk);
    }
    
    @Override
    public String mergeChunks(String uploadId, String originalFileName, int totalChunks) throws IOException {
        logger.debug("本地合并分片: uploadId={}, fileName={}, totalChunks={}", 
                    uploadId, originalFileName, totalChunks);
        return fileStorageService.mergeChunks(uploadId, originalFileName, totalChunks);
    }
    
    @Override
    public boolean deleteFile(String relativePath) {
        logger.debug("本地删除文件: {}", relativePath);
        return fileStorageService.deleteFile(relativePath);
    }
    
    @Override
    public boolean fileExists(String relativePath) {
        return fileStorageService.fileExists(relativePath);
    }
    
    @Override
    public long getFileSize(String relativePath) throws IOException {
        return fileStorageService.getFileSize(relativePath);
    }
    
    @Override
    public String copyFile(String sourceRelativePath, String targetFileName) throws IOException {
        logger.debug("本地复制文件: {} -> {}", sourceRelativePath, targetFileName);
        return fileStorageService.copyFile(sourceRelativePath, targetFileName);
    }

    @Override
    public String copyFile(String sourceRelativePath) throws IOException {
        logger.debug("本地复制文件（自动命名）: {}", sourceRelativePath);
        return fileStorageService.copyFile(sourceRelativePath);
    }
    
    @Override
    public String moveFile(String sourceRelativePath, String targetFileName) throws IOException {
        logger.debug("本地移动文件: {} -> {}", sourceRelativePath, targetFileName);
        return fileStorageService.moveFile(sourceRelativePath, targetFileName);
    }
    
    @Override
    public String generateDownloadUrl(String relativePath, Duration expiration) {
        // 本地存储返回相对路径，但这个方法主要用于FileUrlService
        // 对于直接下载，应该使用FileDownloadController的/{fileId}/download端点
        logger.debug("生成本地下载URL: {}", relativePath);
        return "/api/files/download/" + relativePath;
    }
    
    @Override
    public String generatePreviewUrl(String relativePath, Duration expiration) {
        // 本地存储直接返回相对路径，由 Controller 处理预览
        logger.debug("生成本地预览URL: {}", relativePath);
        return "/api/files/preview/" + relativePath;
    }
    
    @Override
    public String calculateFileSHA256(String relativePath) throws IOException {
        Path filePath = fileStorageService.getAbsolutePath(relativePath);
        return fileStorageService.calculateFileSHA256(filePath);
    }
    
    @Override
    public String calculateChunkMD5(MultipartFile chunk) throws IOException {
        return fileStorageService.calculateChunkMD5(chunk);
    }
    
    @Override
    public String getStorageType() {
        return "local";
    }
    
    @Override
    public void initStorage() {
        logger.info("初始化本地存储目录");
        fileStorageService.initStorageDirectories();
    }

    @Override
    public String getFileExtension(String fileName) {
        return fileStorageService.getFileExtension(fileName);
    }

    @Override
    public void cleanupChunks(String uploadId) {
        logger.debug("清理本地分片文件: {}", uploadId);
        fileStorageService.cleanupChunks(uploadId);
    }
    
    /**
     * 获取文件绝对路径（用于兼容现有代码）
     */
    public Path getAbsolutePath(String relativePath) {
        return fileStorageService.getAbsolutePath(relativePath);
    }
    
    /**
     * 生成存储路径（用于兼容现有代码）
     */
    public String generateStoragePath(String originalFileName) {
        return fileStorageService.generateStoragePath(originalFileName);
    }
    

}
